package co.yixiang.modules.system.rest;

import cn.hutool.core.convert.Convert;
import co.yixiang.logging.aop.log.Log;
import co.yixiang.modules.system.domain.LoanPlan;
import co.yixiang.modules.system.dto.LoanPlanDto;
import co.yixiang.modules.system.dto.queryCriteria.LoanPlanQueryCriteria;
import co.yixiang.modules.system.service.LoanPlanService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.data.domain.Pageable;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * @author zf
 * @date 2021-10-10
 */
@AllArgsConstructor
@Api(tags = "贷款专属方案管理")
@RestController
@RequestMapping("/api/loanPlan")
public class LoanPlanController {

    private final LoanPlanService loanPlanService;

    @Log("导出数据")
    @ApiOperation("导出数据")
    @GetMapping(value = "/download")
    @PreAuthorize("@el.check('admin','loanPlan:list')")
    public void download(HttpServletResponse response, LoanPlanQueryCriteria criteria) throws IOException {
        loanPlanService.download(Convert.toList(LoanPlanDto.class, loanPlanService.queryAll(criteria)), response);
    }

    @GetMapping
    @Log("查询贷款专属方案")
    @ApiOperation("查询贷款专属方案")
    @PreAuthorize("@el.check('admin','loanPlan:list')")
    public ResponseEntity<Object> getLoanPlans(LoanPlanQueryCriteria criteria, Pageable pageable) {
        return new ResponseEntity<>(loanPlanService.queryAll(criteria, pageable), HttpStatus.OK);
    }

    @PostMapping
    @Log("新增贷款专属方案")
    @ApiOperation("新增贷款专属方案")
    @PreAuthorize("@el.check('admin','loanPlan:add')")
    public ResponseEntity<Object> create(@Validated @RequestBody LoanPlan resources) {
        return new ResponseEntity<>(loanPlanService.save(resources), HttpStatus.CREATED);
    }

    @PutMapping
    @Log("修改贷款专属方案")
    @ApiOperation("修改贷款专属方案")
    @PreAuthorize("@el.check('admin','loanPlan:edit')")
    public ResponseEntity<Object> update(@Validated @RequestBody LoanPlan resources) throws Exception {
//        loanPlanService.updateById(resources);
        loanPlanService.check(resources);
        return new ResponseEntity<>(HttpStatus.NO_CONTENT);
    }

    @Log("删除贷款专属方案")
    @ApiOperation("删除贷款专属方案")
    @PreAuthorize("@el.check('admin','loanPlan:del')")
    @DeleteMapping
    public ResponseEntity<Object> deleteAll(@RequestBody List<Integer> ids) {
        loanPlanService.removeByIds(ids);
        return new ResponseEntity<>(HttpStatus.OK);
    }
}